<template>
  <view :="fv.rootProps" @click="change">
    <template v-if="!inlinePrompt">
      <view v-for="item in fv.prompts" :class="item.class">{{ item.text }}</view>
    </template>
    <view :class="[variables.ns.e('box')]">
      <view :class="fv.prompt.class" v-if="inlinePrompt">{{ fv.prompt.text }}</view>
      <view :class="[variables.ns.e('action')]">
        <view v-if="fv.actionIcon" :class="['iconfont', fv.actionIcon]"></view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import { SwitchNS, variables } from '.';

defineOptions({
  name: SwitchNS.name
})
const props = defineProps(SwitchNS.props)
const emits = defineEmits(SwitchNS.emits)
const fv = computed(() => {
  const disabled = props.disabled || props.loading
  const rootProps = {
    class: [
      variables.ns.b,
      variables.ns.s('active', props.modelValue),
      variables.ns.s('disabled', disabled),
      variables.ns.s('loading', props.loading),
      variables.ns.s('inline-prompt', props.inlinePrompt)
    ]
  }
  const prompts = (['inactive', 'active'] as const).map(key => {
    const item = props[key]
    return {
      text: item?.icon ? '' : item?.text,
      class: (item?.icon ? ['iconfont', item.icon] : [])
        .concat(props.inlinePrompt ? variables.ns.e('core') : [variables.ns.e('label'), variables.ns.e(key)])
    }
  })
  const actionIcon = props.loading
    ? 'icon-loading'
    : props.modelValue ? props.active?.actionIcon : props.inactive?.actionIcon
  return {
    rootProps, prompts, prompt: prompts[+Boolean(props.modelValue)], actionIcon, disabled
  }
})

async function change(){
  let is = !props.modelValue

  if (fv.value.disabled) return 
  if (props.beforeChange)  try { await props.beforeChange() } catch (error) { return  }

  emits('update:modelValue', is)
  emits('change', is)
}
</script>